package com.wolf.server;

import com.wolf.annotation.WolfService;
import com.wolf.config.ServerProperties;
import com.wolf.core.BeanMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Method;

/**
 * @auth: dylan
 * @Desc:
 * @Time: 2024/5/2
 */
@Slf4j
public class WolfServerInitializerProcessor implements InitializingBean, BeanPostProcessor {
    private ServerProperties properties;

    public WolfServerInitializerProcessor(ServerProperties properties) {
        this.properties = properties;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //获取bean的注解信息看是否包含WolfService注解
        Class<?> clazz = bean.getClass();
        if(!clazz.isAnnotationPresent(WolfService.class)){
            //不需要初始化映射
            return bean;
        }
        Method[] methods = clazz.getDeclaredMethods();
        String beanMapKey;
        //遍历方法并设置全局映射
        for (Method method:methods){
            beanMapKey=clazz.getInterfaces()[0].getName()+"."+method.getName();
            BeanMethod beanMethod = new BeanMethod();
            beanMethod.setBean(bean);
            beanMethod.setMethod(method);
            BeanDispatcher.getInstance().BEAN_METHOD_CONTAINER.put(beanMapKey,beanMethod);
        }
        return bean;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //初始化的时候,初始化NettyServer
        log.info("begin initialize NettyServer on port:{}",properties.getPort());
        new Thread(new WolfNettyServer(properties)).start();
    }

}
